<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      background
      border
      height="640"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <exports
      :visible.sync="show"
      @close="close"
      @input="setImportDataId"
    ></exports>
    <detail :id="id" :visible.sync="detailShow" @close="close"></detail>
  </lb-layout>
</template>

<script>
import auth from "@/plugins/auth";
import { list, quotaAssess, rationVersionList } from "@/api/quota/energy";
import exports from "@/views/work/quota/energy/components/exports.vue";
import CascaderSelect from "@/components/Select/CascaderSelect";
import detail from "@/views/work/quota/energy/components/detail.vue";
import { mul, formatDate } from "@/utils/index";
export default {
  name: "energy",
  filters: {
    dictFee(val) {
      const text = val ? mul(val, 100) + "%" : "";
      return text;
    },
    formatTime(val) {
      const text = val ? formatDate(val) : "";
      return text;
    },
  },
  dicts: ["energy_type", "target_type"],
  components: { CascaderSelect, exports, detail },
  data() {
    return {
      id: "",
      show: false,
      detailShow: false,
      versionOption: [],
      // 遮罩层
      loading: false,
      // 表格树数据
      currentPage: 1,
      pageSize: 20,
      total: 0,
      apsForm: {
        formRef: "form",
        labelWidth: "120px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            deptId: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      values={that.$refs?.form?.getFieldsValue().deptId}
                      value={that.$refs?.form?.getFieldsValue().deptId}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"用能单位"}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            refRationCriterionVersion: {
              typeName: "el-select",
              display: true,
              render: (h) => {
                let that = this;
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().refRationCriterionVersion;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "额度标准版本号",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "refRationCriterionVersion",
                            value
                          );
                        },
                      },
                    },
                    [
                      that.versionOption.map((item) => {
                        return h("el-option", {
                          props: {
                            label: item,
                            value: item,
                            key: item,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            energyType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.energy_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().energyType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "能耗种类",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("energyType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            targetType: {
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.target_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().targetType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "指标类型",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("targetType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            refRationCriterionYear: {
              typeName: "el-date-picker",
              type: "year",
              "value-format": "yyyy",
              placeholder: "额度分配年份",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              display: true,
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              display: true,
              click: this.handleReset,
            },
            {
              label: "额度评估",
              type: "primary",
              typeName: "el-button",
              plain: true,
              size: "small",
              display: true,
              click: () => this.handleAss(),
            },
            {
              label: "导入实际能耗",
              type: "primary",
              typeName: "el-button",
              plain: true,
              size: "small",
              display: true,
              click: () => (this.show = true),
            },
            {
              label: "评估报告",
              type: "warning",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-upload2",
              plain: true,
              click: () => this.openFile(),
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            label: "用能单位",
            prop: "deptName",
            minWidth: 150,
            showOverflowTooltip: true,
          },
          {
            label: "能耗分配年度",
            prop: "refRationCriterionYear",
            width: 150,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "refRationCriterionVersion",
          //   label: "版本号",
          //   showOverflowTooltip: true,
          //   minWidth: 150,
          // },
          {
            prop: "assessGuideVal",
            label: "评估能耗额度引导值E1(kwh/m2)",
            width: 240,
            showOverflowTooltip: true,
          },
          {
            prop: "assessBaseVal",
            label: "评估能耗额度基准值E2(kwh/m2)",
            width: 240,
            showOverflowTooltip: true,
          },
          {
            prop: "assessConstraintVal",
            label: "评估能耗额度约束值E3(kwh/m2)",
            width: 240,
            showOverflowTooltip: true,
          },
          {
            prop: "refEnergyTotal",
            label: "参考实际能耗值（kwh/m2）",
            width: 220,
            showOverflowTooltip: true,
          },
          {
            prop: "refAllocationGuideVal",
            label: "参考能耗额度引导值A0(kwh/m2)",
            width: 249,
            showOverflowTooltip: true,
          },
          {
            prop: "refAllocationBaseVal",
            label: "参考能耗额度基准值B0(kwh/m2)",
            width: 249,
            showOverflowTooltip: true,
          },
          {
            prop: "refAllocationConstraintVal",
            label: "参考能耗额度约束值C0(kwh/m2)",
            width: 249,
            showOverflowTooltip: true,
          },
          // {
          //   prop: "energyType",
          //   label: "能耗种类",
          //   minWidth: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.energy_type}
          //           value={scope.row.energyType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          // {
          //   prop: "targetType",
          //   label: "指标类型",
          //   minWidth: 150,
          //   align: "center",
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.target_type}
          //           value={scope.row.targetType}
          //         />
          //       </div>
          //     );
          //   },
          // },
          {
            label: "操作",
            width: "120",
            fixed: "right",
            render: (h, scope) => {
              let c;
              c = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  onClick={() => {
                    this.detail(scope.row.id);
                  }}
                >
                  详情
                </el-button>
              );
              return <div>{c}</div>;
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {
    // this.queryParams.refRationCriterionYear = new Date().getFullYear() + "";
    this.judgePermi();
    this.getVersionList();
    this.handlerSearchDetail();
  },
  methods: {
    judgePermi() {
      // 搜索 重置
      if (auth.hasPermi("energy:assess:list")) {
        this.apsForm.formConfig.formSoltButton[0].display = false;
        this.apsForm.formConfig.formSoltButton[1].display = false;
      }
      if (auth.hasPermi("energy:assess:quotaAssess")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
      if (auth.hasPermi("energy:assess:import")) {
        this.apsForm.formConfig.formSoltButton[3].display = false;
      }
      // 额度标准版本号
      if (auth.hasPermi("energy:criterion:versionList")) {
        this.apsForm.formConfig.properties.refRationCriterionVersion.display = false;
      }
    },
    headerRowStyle(obj) {
      if (
        obj.column.property === "assessGuideVal" ||
        obj.column.property === "assessBaseVal" ||
        obj.column.property === "assessConstraintVal"
      ) {
        return "tabel-bg-green";
      }
      if (
        obj.column.property === "refAllocationGuideVal" ||
        obj.column.property === "refAllocationConstraintVal"
      ) {
        return "tabel-bg-blue";
      }
    },
    tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        return "background:rgba(223,240,216,0.4)";
      } else if (columnIndex === 3) {
        return "background:rgba(242,222,222,0.4)";
      } else if (columnIndex === 4) {
        return "background:rgba(217,237,247,0.4)";
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 6) {
        if (rowIndex % this.list.length === 0) {
          return {
            rowspan: this.list.length,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    detail(id) {
      this.id = id;
      this.detailShow = true;
    },
    //评估报告
    openFile() {
      window.open(
        "http://192.168.1.44:28080/profile/upload/2022/08/12/ceshi_20220812164606A002.png",
        "_blank"
      );
    },
    handlerLiandong(val) {
      let result;
      if (val && val.length > 0) {
        result = val[val.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("deptId", val[val.length - 1]);
    },
    //获取版本号
    getVersionList() {
      rationVersionList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.versionOption = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300064");
        });
    },
    close(status) {
      this.show = false;
    },
    setImportDataId(data) {
      this.$refs?.form?.setFieldValue("importDataId", data);
      this.handlerSearchDetail();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300081");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    /** 额度评估 */
    handleAss() {
      const data = this.$refs?.form.getFieldsValue();
      if (!data.deptId) {
        this.$message.warning("请选择用能单位");
        return false;
      }
      if (!data.energyType) {
        this.$message.warning("请选择能耗种类");
        return false;
      }
      if (!data.targetType) {
        this.$message.warning("请选择指标类型");
        return false;
      }
      if (!data.refRationCriterionVersion) {
        this.$message.warning("请选择额度标准版本号");
        return false;
      }
      if (!data.refRationCriterionYear) {
        this.$message.warning("请选择参考实际能耗数年份");
        return false;
      }
      quotaAssess(data)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleReset();
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300062");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .tabel-bg-green {
  background: rgba(223, 240, 216, 0.4) !important;
}

::v-deep .tabel-bg-blue {
  background: rgba(217, 237, 247, 0.4) !important;
}
</style>
